package com.ysjy.course.controller;

import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.dto.course.CourseClassDto;
import com.wkbb.common.utils.StringUtil;
import com.ysjy.course.dto.*;
import com.ysjy.course.model.ClassChangeApply;
import com.ysjy.course.model.OrgCourse;
import com.ysjy.course.model.SignUpUser;
import com.ysjy.course.service.CourseClassService;
import com.ysjy.course.service.SignUpUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(description = "课班管理")
@RequestMapping("/course/class/manage")
@Slf4j
public class CourseClassManageController extends BaseController {

    @Autowired
    private CourseClassService courseClassService;
    @Autowired
    private SignUpUserService signUpUserService;

    @ApiOperation(value = "新增 or 编辑课班",notes = "{\"className\":\"课程班1\",\"orgId\":1452,\"orgName\":\"紫城中学\",\"classType\":4,\"serviceUniqueId\":\"2022052011076175\"}")
    @RequestMapping(value = "putCourseClass", method = RequestMethod.POST)
    public ResultDTO<Boolean> putCourseClass( @Valid @RequestBody CourseClassDto data){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getOrgId() == null || data.getOrgName() == null || data.getClassType() == null || data.getServiceUniqueId() == null){
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            data.setCreateBy(userDto.getName());
            return courseClassService.putCourseClass(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "课表重新生成")
    @RequestMapping(value = "generateCourseTime", method = RequestMethod.POST)
    public ResultDTO<Boolean> generateCourseTime(
            @ApiParam(value = "服务标识（机构课程uniqueId or 托管uniqueId）", required = false) @RequestParam(name = "serviceUniqueId", required = false) String serviceUniqueId,
            @ApiParam(value = "班级类型 4课程班 5托管班", required = false) @RequestParam(name = "classType", required = false) Integer classType,
            @ApiParam(value = "班级关联ID", required = false) @RequestParam(name = "classId", required = false) Long classId){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseClassService.generateCourseTime(serviceUniqueId,classType,classId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "课班列表")
    @RequestMapping(value = "getCourseClassListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<CourseClassDto>> getCourseClassListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "班级名称（模糊搜索）", required = false) @RequestParam(name = "className", required = false) String className,
            @ApiParam(value = "课程名称（模糊搜索）", required = false) @RequestParam(name = "serviceName", required = false) String serviceName,
            @ApiParam(value = "学年", required = false) @RequestParam(name = "serviceYear", required = false) String serviceYear,
            @ApiParam(value = "班级类型 4课程班 5托管班", required = false) @RequestParam(name = "classType", required = false) Integer classType,
            @ApiParam(value = "状态 0未报名 1报名中 2未开课 3开课中 4已结课", required = false) @RequestParam(name = "status", required = false) Integer status,
            @ApiParam(value = "排序方式 1综合 2报名人数 3开班时间", required = false) @RequestParam(name = "sortWay", required = false) Integer sortWay,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (sortWay == null) sortWay = 1;
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(className)) params.put("className", className);
            if (!StringUtil.isEmpty(serviceName)) params.put("serviceName", serviceName);
            if (!StringUtil.isEmpty(serviceYear)) params.put("serviceYear", serviceYear);
            params.put("orgId", orgId);
            params.put("classType", classType);
            params.put("status", status);
            params.put("sortWay", sortWay);
            PageInfo<CourseClassDto> pageInfo = courseClassService.getListByPage(params, pageNo, pageSize);
            for (CourseClassDto dto:pageInfo.getList()){
                dto.initStatus();
            }
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "考勤管理-考勤列表")
    @RequestMapping(value = "getCourseTimeAttendListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<AttendDto>> getCourseTimeAttendListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "班级名称（模糊搜索）", required = false) @RequestParam(name = "className", required = false) String className,
            @ApiParam(value = "课程名称（模糊搜索）", required = false) @RequestParam(name = "serviceName", required = false) String serviceName,
            @ApiParam(value = "教师姓名（模糊搜索）", required = false) @RequestParam(name = "teacherName", required = false) String teacherName,
            @ApiParam(value = "班级类型 4课程班 5托管班", required = false) @RequestParam(name = "classType", required = false) Integer classType,
            @ApiParam(value = "开始时间 例：2022-07-29", required = false) @RequestParam(name = "startDate", required = false) String startDate,
            @ApiParam(value = "截止时间 例：2022-08-04", required = false) @RequestParam(name = "endDate", required = false) String endDate,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(className)) params.put("className", className);
            if (!StringUtil.isEmpty(serviceName)) params.put("serviceName", serviceName);
            if (!StringUtil.isEmpty(teacherName)) params.put("teacherName", teacherName);
            if (!StringUtil.isEmpty(startDate)) params.put("startDate", startDate);
            if (!StringUtil.isEmpty(endDate)) params.put("endDate", endDate);
            params.put("orgId", orgId);
            params.put("classType", classType);
            PageInfo<AttendDto> pageInfo = courseClassService.getCourseTimeAttendListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "考勤管理-课时考勤详情 学生列表(请假状态)")
    @RequestMapping(value = "getCourseTimeAttendStuList", method = RequestMethod.GET)
    public ResultDTO<List<CourseAttendDto>> getCourseTimeAttendStuList(
            @ApiParam(value = "课时ID", required = false) @RequestParam(name = "courseTimeId", required = false) String courseTimeId
    ) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(courseTimeId)) params.put("courseTimeId", courseTimeId);
            List<CourseAttendDto> list = courseClassService.getCourseTimeAttendStuList(params);
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取课班详情")
    @RequestMapping(value = "getCourseClass", method = RequestMethod.GET)
    public ResultDTO<CourseClassDto> getCourseClass(
            @ApiParam(value = "课班classId", required = false) @RequestParam(name = "classId", required = true) Integer classId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseClassService.getCourseClass(classId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "申请调班审核")
    @RequestMapping(value = "auditChangeClass", method = RequestMethod.POST)
    public ResultDTO<Boolean> auditChangeClass(
            @ApiParam(value = "申请ID", required = false) @RequestParam(name = "id", required = true) Long id,
            @ApiParam(value = "状态 1同意 2拒绝", required = false) @RequestParam(name = "state", required = true) Integer state) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseClassService.auditChangeClass(id,state,userDto);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "申请调班列表")
    @RequestMapping(value = "getChangeClassApplyListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<ClassChangeApply>> getChangeClassApplyListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "状态 0申请调班 1已同意 2已拒绝", required = false) @RequestParam(name = "state", required = false) Integer state,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            params.put("state", state);
            PageInfo<ClassChangeApply> pageInfo = courseClassService.getChangeClassApplyListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "课班学生列表")
    @RequestMapping(value = "getCourseClassStudentListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<SignUpUserDto>> getCourseClassStudentListByPage(
            @ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) String classId,
            @ApiParam(value = "商品唯一标识 （课程、托管uniqueId）", required = false) @RequestParam(name = "goodNumber", required = false) String goodNumber,
            @ApiParam(value = "学生姓名、手机号（模糊搜索）", required = false) @RequestParam(name = "filter", required = false) String filter,
            @ApiParam(value = "状态：0在班 1已退班", required = false) @RequestParam(name = "refundStatus", required = false) Integer refundStatus,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(filter)) params.put("filter", filter);
            if (!StringUtil.isEmpty(goodNumber)) params.put("goodNumber", goodNumber);
            params.put("refundStatus", refundStatus);
            params.put("classId", classId);
            PageInfo<SignUpUserDto> pageInfo = courseClassService.getCourseClassStudentListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "可调课班列表")
    @RequestMapping(value = "getAdjustableCourseClassList", method = RequestMethod.GET)
    public ResultDTO<List<CourseClassDto>> getAdjustableCourseClassList(
            @ApiParam(value = "机构ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "当前班级ID", required = true) @RequestParam(name = "classId", required = true) Long classId
    ) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            //可以报名
            params.put("canSignUp", true);
            params.put("classId", classId);
            List<CourseClassDto> list = courseClassService.getListByMapParams(params);
            for (CourseClassDto dto:list){
                dto.initStatus();
            }
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "学生调班")
    @RequestMapping(value = "stuChangeClass", method = RequestMethod.POST)
    public ResultDTO<Boolean> stuChangeClass(
            @ApiParam(value = "学生报名id", required = true) @RequestParam(name = "signUpUserId", required = true) Long signUpUserId,
            @ApiParam(value = "新班级id", required = true) @RequestParam(name = "newClassId", required = true) Long newClassId,
            @ApiParam(value = "调班原因", required = false) @RequestParam(name = "way", required = false) String way
    ){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseClassService.stuChangeClass(signUpUserId,newClassId,way,userDto);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "学生退费")
    @RequestMapping(value = "refund", method = RequestMethod.POST)
    public ResultDTO<Boolean> refund(
            @ApiParam(value = "学生报名id", required = true) @RequestParam(name = "signUpUserId", required = true) Long signUpUserId,
            @ApiParam(value = "退款金额(分)", required = true) @RequestParam(name = "refundAmount", required = true) Integer refundAmount,
            @ApiParam(value = "退款原因", required = false) @RequestParam(name = "refundWhy", required = false) String refundWhy
    ){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return signUpUserService.refund(signUpUserId,refundAmount,refundWhy,userDto);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "获取学生报班信息列表")
    @RequestMapping(value = "getCourseClassListByStudent", method = RequestMethod.GET)
    public ResultDTO<List<CourseClassDto>> getCourseClassListByStudent(
            @ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            List<CourseClassDto> list = courseClassService.getCourseClassListByStudent(params);
            for (CourseClassDto dto:list){
                dto.initStatus();
            }
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取教师课时反馈分页列表")
    @RequestMapping(value = "getTeacherCourseTimeFeedbackListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<TeacherCourseTimeFeedbackDto>> getTeacherCourseTimeFeedbackListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "班级名称（模糊搜索）", required = false) @RequestParam(name = "className", required = false) String className,
            @ApiParam(value = "课程名称（模糊搜索）", required = false) @RequestParam(name = "serviceName", required = false) String serviceName,
            @ApiParam(value = "教师姓名（模糊搜索）", required = false) @RequestParam(name = "teacherName", required = false) String teacherName,
            @ApiParam(value = "班级类型 4课程班 5托管班", required = false) @RequestParam(name = "classType", required = false) Integer classType,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize
    ) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(className)) params.put("className", className);
            if (!StringUtil.isEmpty(serviceName)) params.put("serviceName", serviceName);
            if (!StringUtil.isEmpty(teacherName)) params.put("teacherName", teacherName);
            params.put("orgId", orgId);
            params.put("classType", classType);
            PageInfo<TeacherCourseTimeFeedbackDto> pageInfo = courseClassService.getTeacherCourseTimeFeedbackListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

}